<?php

namespace app\models;

use Yii;
use yii\base\Model;
use app\models\User;
use yii\log\Logger;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class RemarkForm extends Model
{
    public $content;
    public $next_follow_at;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['content', 'next_follow_at'], 'required'],
            ['next_follow_at', 'datetime','format'=>'yyyy-MM-dd HH:mm:ss'],
            ['next_follow_at', 'filter','filter'=>function($value){
                return strtotime($value);
            }],
        ];
    }

    public function attributeLabels()
    {
        return [
            'content' => '备注内容',
            'next_follow_at' => '下次跟进时间'
        ];
    }

    public function save()
    {
        if ($this->validate()){
            $db = Yii::$app->db;
            $transaction = $db->beginTransaction();
            try{
                $follow_at = time();
                $project_id = Yii::$app->request->get('id');
                $db->createCommand()->insert('project_remark',[
                    'project_id' => $project_id,
                    'content' => $this->content,
                    'next_follow_at' => $this->next_follow_at,
                    'user_id' => Yii::$app->user->identity->id,
                    'created_at' => $follow_at,
                    'updated_at' => $follow_at,
                ])->execute();
                $db->createCommand()->update('project',[
                    'follow_at' => $follow_at,
                    'next_follow_at' => $this->next_follow_at,
                    'follow_user_id' => Yii::$app->user->identity->id,
                ],['id'=>$project_id])->execute();
                $transaction->commit();
                return true;
            }catch (\Exception $exception){
                $transaction->rollBack();
                return false;
            }
        }
        return false;
    }

}
